/*
 * MIT License
 *
 * Copyright (c) 2020 Mr.css
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

package cn.seaboot.postman.root.analyzer;

import cn.seaboot.common.core.CommonUtils;
import cn.seaboot.common.core.FastJsonUtils;
import cn.seaboot.postman.PostmanConfiguration;
import cn.seaboot.postman.analyzer.ControllerInfo;
import cn.seaboot.postman.analyzer.FormType;
import cn.seaboot.postman.analyzer.MethodInfo;
import cn.seaboot.postman.request.Body;
import cn.seaboot.postman.request.Query;
import cn.seaboot.postman.request.Request;
import cn.seaboot.postman.request.Url;
import cn.seaboot.postman.response.BodyField;
import cn.seaboot.postman.response.Response;
import cn.seaboot.postman.root.Item;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Mr.css
 * @date 2022-02-10 15:23
 */
public class DefaultApiAnalyzer implements ApiAnalyzer {
    private Logger logger = LoggerFactory.getLogger(DefaultApiAnalyzer.class);

    /**
     * URL分隔符
     */
    private final static char SPE = '/';
    /**
     * URL分隔符
     */
    private final String SPE_STR = String.valueOf(SPE);
    /**
     * 共享变量，url地址使用共享变量来做
     */
    private final static String BASE_URL = "{{baseUrl}}";
    /**
     * 不支持并发，不过作为OpenAPI，应该不会出问题
     */
    private PostmanConfiguration configuration;


    /**
     * {@inheritDoc}
     *
     * @param configuration
     * @param controllerInfo controller' Class
     * @return
     */
    @Override
    public @Nullable List<Item> searchApiFromController(PostmanConfiguration configuration, ControllerInfo controllerInfo) {
        this.configuration = configuration;
        //一个Controller分析出1组的API，ret的长度始终是1
        List<Item> ret = new ArrayList<>();

        //search all api form controller's method
        List<Item> controllerApi = new ArrayList<>();
        for (MethodInfo method : controllerInfo.getMethodInfos()) {
            logger.debug("开始解析函数：" + method.getMethod().getName());
            List<Query> queries = configuration.analyzeQuery(method);
            this.searchApiFormMethod(controllerInfo, method, queries, controllerApi);
        }

        //将Controller所有的接口，封装成一个Item对象
        if (CommonUtils.isNotEmpty(controllerApi)) {
            Item groupItem = new Item();
            groupItem.setName(controllerInfo.getControllerDescription());
            groupItem.setItem(controllerApi.toArray(new Item[]{}));
            ret.add(groupItem);
        }
        return ret;
    }

    /**
     * 为了避免过多的循环，这个函数不需要再拆分
     * <p>
     * Get a api-group form a method, and add result into controllerApi.
     *
     * @param controllerInfo   -
     * @param controllerMethod -
     * @param queryList        -
     * @param controllerApi    api of a controller
     */
    private void searchApiFormMethod(ControllerInfo controllerInfo, MethodInfo controllerMethod, List<Query> queryList, List<Item> controllerApi) {
        String requestMethod = controllerMethod.getRequestMethod();
        String requestDescription = controllerMethod.getMethodDescription();

        Body body = null;
        Query[] queries = null;
        //根据表单类型，将请求参数转换成不同格式的数据
        if (controllerMethod.getFormType() == FormType.BODY) {
            //RequestBody
            body = configuration.convertToRequestBody(queryList);
        } else if (controllerMethod.getFormType() == FormType.FILE) {
            //FormData
            body = configuration.convertToFormData(controllerMethod, queryList);
        } else {
            //简单Form
            queries = queryList.toArray(new Query[]{});
        }

        //获取响应数据样例
        Response[] responses = null;
        List<Response> responseList = this.getResponse(controllerMethod);
        if (CommonUtils.isNotEmpty(responseList)) {
            responses = responseList.toArray(new Response[0]);
        }

        //根据Controller和Method的Url，拼接出全路径，构造出每一个请求所需的全部参数
        for (String ctrlUrl : controllerInfo.getRequestPath()) {
            for (String methodUrl : controllerMethod.getRequestPath()) {
                //解析Url
                Url url = this.getUrl(ctrlUrl, methodUrl);
                //解析Request
                Request request = new Request();
                request.setMethod(requestMethod);
                request.setDescription(requestDescription);
                request.setUrl(url);
                request.setBody(body);
                url.setQuery(queries);

                Item item = new Item();
                item.setName(request.getDescription());
                item.setRequest(request);
                controllerApi.add(item);

                //解析Response
                if (responses != null) {
                    responseList.forEach(e -> e.setOriginalRequest(request));
                    item.setResponse(responses);
                }
            }
        }
    }


    /**
     * 获取一个Method的Response数据样例
     * <p>
     * generate {@link Response}
     *
     * @param method method
     * @return List<Response>
     */
    private List<Response> getResponse(MethodInfo method) {
        BodyField bodyField = configuration.analyzeBodyField(method);
        if (bodyField == null) {
            return null;
        }
        String json = FastJsonUtils.toJSONString(bodyField);

        //Create a {@link Response} which contain BodyField.
        Response response = new Response();
        response.setName("Response 详情");
        response.setBody(json);

        //Create any others {@link Response}
        List<Response> responses = configuration.createResponse(bodyField);

        //result
        responses.add(response);
        return responses;
    }

    /**
     * 获取每一个请求的访问路径
     * <p>
     * Concat controller-mapping and method-mapping, and return a longer url, which will start with '/';
     * {@link Url}
     *
     * @param baseUrl controller mapping
     * @param mapping method mapping
     * @return raw
     */
    private Url getUrl(String baseUrl, String mapping) {
        String subRaw = baseUrl + mapping;
        String raw = BASE_URL + subRaw;
        String[] path = subRaw.substring(1).split(SPE_STR);
        Url url = new Url();
        url.setHost(configuration.getHost());
        url.setProtocol(configuration.getProtocol());
        url.setRaw(raw);
        url.setPath(path);
        return url;
    }
}
